package com.material.vtool.service.impl;

import com.material.vtool.entity.BTeamInfoEntity;
import com.material.vtool.entity.BTeamRelationEntity;
import com.material.vtool.entity.combinedEntity.CombinedTeamEntity;
import com.material.vtool.entity.respEntity.ReturnCode;
import com.material.vtool.exception.ServiceException;
import com.material.vtool.mapper.TeamInfoMapper;
import com.material.vtool.mapper.TeamRelationMapper;
import com.material.vtool.service.TeamInfoService;
import com.material.vtool.utils.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class TeamInfoServiceImpl implements TeamInfoService {
    @Autowired
    private TeamInfoMapper teamInfoMapper;

    @Autowired
    private TeamRelationMapper teamRelationMapper;

    @Override
    @Transactional
    public int saveTeamInfo(BTeamInfoEntity bTeamInfoEntity) {
        // 1、保存团队信息
        Integer affectedCount = teamInfoMapper.insertTeamInfo(bTeamInfoEntity);
        if (affectedCount == null || affectedCount.intValue() == 0) throw new ServiceException("保存失败", ReturnCode.SERVER_ERROR);

        Integer userId = bTeamInfoEntity.getUserId();
        Integer teamId = bTeamInfoEntity.getId();

        // 2、创建人为创始人,保存到团队成员中
        BTeamRelationEntity bTeamRelationEntity = new BTeamRelationEntity();
        bTeamRelationEntity.setUserId(userId);
        bTeamRelationEntity.setTeamId(teamId);
        bTeamRelationEntity.setTeamRole(Integer.valueOf(2));// 设置为创始人
        bTeamRelationEntity.setUserFlag(Integer.valueOf(1));// 设置该团队为活跃团队
        bTeamRelationEntity.setCreateTime(DateUtil.getCurDate());
        Integer affectedCount1 = teamRelationMapper.insertTeamRelation(bTeamRelationEntity);
        if (affectedCount1 == null || affectedCount1.intValue() == 0) throw new ServiceException("保存失败", ReturnCode.SERVER_ERROR);

        // 3、更新创始人的其他团队为不活跃状态
        teamRelationMapper.updateUserFlag(userId, teamId);

        return affectedCount;
    }

    @Override
    public int updateTeam(BTeamInfoEntity bTeamInfoEntity) {
        int affectedCount = teamInfoMapper.updateTeamInfo(bTeamInfoEntity);
        if (affectedCount == 0) throw new ServiceException("更新失败", ReturnCode.SERVER_ERROR);
        return affectedCount;
    }

    @Override
    public List<CombinedTeamEntity> getTeamByIdOrName(String miniCode, String key) {
        return teamInfoMapper.getTeamByIdOrName(miniCode, key);
    }

    @Override
    public BTeamInfoEntity getTeamInfoByTeamId(Integer teamId) {
        return teamInfoMapper.getTeamInfoByTeamId(teamId);
    }
}
